/*
从某个设备读取若干字节，非阻塞IO方式
*/

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_SIZE_MAX 1024

int main(int argc, char **argv)
{
    char buffer[BUFFER_SIZE_MAX] = {0};

    if (argc != 3)
    {
        printf("usage:%s <dev> <N bytes>\n", argv[0]);
        return -1;
    }
    const char *dev = argv[1];
    const unsigned long n = strtoul(argv[2], NULL, 10);

    if (n > BUFFER_SIZE_MAX)
    {
        printf("n must less than %d\n", BUFFER_SIZE_MAX);
        return -1;
    }

    int fd = open(dev, O_CLOEXEC | O_RDONLY | O_NONBLOCK);
    if (fd < 0)
    {
        printf("open error(%s)\n", strerror(errno));
        return -1;
    }

    ssize_t read_n = read(fd, buffer, n);
    if (read_n < 0)
    {
        printf("read error(%s)\n", strerror(errno));
        close(fd);
        return -1;
    }
    printf("read_n=%ld,read(%s) from %s\n", read_n, buffer, dev);

    close(fd);

    return 0;
}